<?php
namespace Home\Model;
use Think\Model;
class AddressModel extends Model{
    // protected $patchValidate = true;
    public $m_data = array();


    protected $_validate = array(
        array('username','not_empty','真实姓名不得为空',1,'function'),
        array('prov','not_empty','请选择省份',1,'function'),
        array('city','not_empty','请选择城市',1,'function'),
        array('dist','not_empty','请选择地区',1,'function'),
        array('address','not_empty','街道地址不得为空',1,'function'),
        array('code','/^[0-9]{6}$/','邮编格式不正确'),
        array('mobile','is_mobile','手机格式不正确',1,'function'),
        array('id','require','非法操作',2),
    );

    protected $_auto = array (
        array('c_time','time',1,'function'), // 对c_time字段在新增的时候写入当前时间戳
        array('u_time','time',3,'function'), // 对u_time字段在新增和更新的时候写入当前时间戳
    );

    public function setData($data){
        $this->m_data = $data;
    }

    public function getData(){
        return $this->m_data;
    }

    

    /**
     * 插入到数据库
     * @return bool|mixed
     */
    public function insertDb(){
        if(!$this->create($this->m_data,1)){
            //自动验证出错 返回false 让控制器报错
            return false;
        }

        //通过自动验证
        $res = $this->add();
        if($res){
            $data = $this->getData();

            //没有默认地址 默认帮他选
            $one = M('User')->field('address_id')->find($data['user_id']);
            if(!$one['address_id']){
                $wh['id'] =  $data['user_id'];
                $wh['address_id'] = $res;
                M('User')->data($wh)->save();
            }
            return $res;
        }else{
            return false;
        }
    }

    /**
     * 修改到数据库
     * @return bool
     */
    public function updateDb(){
        if(!$this->create($this->m_data,2)){
            return false;
        }
        $res = $this->save();
        return $res;
    }


}
?>